package com.example.demo.binary;

/**
 * 中文和unicode互转
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/03/13 12:29
 */
public class ChineseToUnicode {

    public static void main(String[] args) {
        String str = "你好，我是阜阳人";
        String unicodeStr = chineseToUnicode(str);
        System.out.println(unicodeStr);

        String unicode = unicodeToChineseWithSpace(unicodeStr);
        System.out.println(unicode);
    }

    /**
     * 中文字符串转成unicode字符串
     *
     * @param chineseStr 中文字符串
     * @return String unicode字符串 空格隔开每个字符
     */
    public static String chineseToUnicode(String chineseStr) {
        char[] chars = chineseStr.toCharArray();
        StringBuilder sl = new StringBuilder();
        for (char c : chars) {
            String hexString = Integer.toHexString(c);
            if (hexString.length() <= 2) {
                hexString = "00" + hexString;
            }
            sl.append("\\u").append(hexString).append(" ");
        }
        return sl.toString().trim();
    }

    /**
     * unicode字符串转成中文字符串
     *
     * @param hexString unicode字符串 空格隔开
     * @return String 中文字符串
     */
    public static String unicodeToChineseWithSpace(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        return unicodeToChinese(hexString);
    }

    /**
     * unicode字符串转成中文字符串
     *
     * @param hexString unicode字符串
     * @return String 中文字符串
     */
    public static String unicodeToChinese(String hexString) {
        StringBuilder sl = new StringBuilder();
        String[] splits = hexString.split("\\\\u");
        for (String split : splits) {
            if ("".equals(split)) {
                continue;
            }
            int i = Integer.parseInt(split, 16);
            sl.append((char) i);
        }
        return sl.toString();
    }

    /**
     * unicode字符串转成中文字符串
     *
     * @param hexString unicode字符串
     * @return String 中文字符串
     */
    public static String unicodeToChinese2(String hexString) {
        int start = 0;
        int end = 0;
        StringBuilder sl = new StringBuilder();
        while (start > -1) {
            end = hexString.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = hexString.substring(start + 2, hexString.length());
            } else {
                charStr = hexString.substring(start + 2, end);
            }
            // 16进制parse整形字符串。
            char letter = (char) Integer.parseInt(charStr, 16);
            sl.append(letter);
            start = end;
        }
        return sl.toString();
    }

}
